package cs419.magnusmi.trackitcs;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

public class EditItem extends ActionBarActivity {

    //text views for each field to be displayed
    TextView ID;
    TextView Name;
    TextView Serial;
    TextView Accessories;
    TextView SpecialFeatures;
    TextView OperatingSystem;
    TextView Pages;
    TextView OtherInfo;
    TextView CheckoutStatus;
    Button DeleteBtn;
    Context k;


    //for progress display
    private View mEditDetailView;
    private View mEditDetailStatusView;
    private TextView mEditDetailStatusMessageView;

    //asynchronous task to get data
    ItemEditTask iEditItem;

    //item id to get data for
    String IDnum;
    Button cancel;
    Button save;

    //session vars
    String user;
    String API;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_item);

        //get number of item from intent
        Intent start = getIntent();
        IDnum = start.getStringExtra("id");

        //store session vars
        user = start.getStringExtra("user");
        API = start.getStringExtra("API");

        k = this;

        //establish text views
        ID = (TextView) findViewById(R.id.textView);
        Name = (TextView) findViewById(R.id.textView2);
        Serial = (TextView) findViewById(R.id.textView3);
        Accessories = (TextView) findViewById(R.id.textView4);
        SpecialFeatures = (TextView) findViewById(R.id.textView5);
        OperatingSystem = (TextView) findViewById(R.id.textView6);
        Pages = (TextView) findViewById(R.id.textView7);
        OtherInfo = (TextView) findViewById(R.id.textView8);
        CheckoutStatus = (TextView) findViewById(R.id.textView9);

        //set text views to current values (passed in from item detail view)
        ID.setText(start.getStringExtra("id"));
        Name.setText(start.getStringExtra("Name"));
        Serial.setText(start.getStringExtra("Serial"));
        Accessories.setText(start.getStringExtra("Accessories"));
        SpecialFeatures.setText(start.getStringExtra("SpecialFeatures"));
        OperatingSystem.setText(start.getStringExtra("OperatingSystem"));
        Pages.setText(start.getStringExtra("Pages"));
        OtherInfo.setText(start.getStringExtra("OtherInfo"));
        CheckoutStatus.setText(start.getStringExtra("CheckoutStatus"));


        //for delete button
        DeleteBtn = (Button) findViewById(R.id.deleteBtn);
        DeleteBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {


                AlertDialog.Builder error = new AlertDialog.Builder(k);
                        error.setTitle("Delete Item");
                        error.setMessage("Are you sure you want to permanently delete this item");
                        error.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent i = new Intent(getApplicationContext(), Delete.class);
                                Utility.addToIntent(i, user, API);
                                i.putExtra("id", IDnum.toString());
                                startActivity(i);

                            }
                        });
                        error.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // do nothing
                            }
                        });
                        error.show();
            }
        });

        //for spinner wheel
        mEditDetailView = findViewById(R.id.editDetail_form);
        mEditDetailStatusView = findViewById(R.id.editDetail_status);
        mEditDetailStatusMessageView = (TextView)findViewById(R.id.editDetail_status_message);

        //cancel button: returns to itemview
        cancel = (Button) findViewById(R.id.cancelBtn3);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(), ItemView.class);
                i.putExtra("id", IDnum);
                Utility.addToIntent(i,user, API);
                startActivity(i);
            }
        });

        //save button: triggers save attempt
        save = (Button) findViewById(R.id.editBtn);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptEdit();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu (Menu menu)  {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.logout:
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //clear stack to enforce logout (http://stackoverflow.com/questions/3007998/on-logout-clear-activity-history-stack-preventing-back-button-from-opening-l)
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                return true;
            case R.id.inventory_menu:
                Intent j = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(j, user, API);
                startActivity(j);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void attemptEdit() {
        if (iEditItem != null) {
            return;
        }

        // Reset errors.
        Name.setError(null);
        Serial.setError(null);
        Pages.setError(null);

        // create new Item object
        Item newItem = new Item(ID.getText().toString(), Name.getText().toString(), Serial.getText().toString(),
                Pages.getText().toString(), Accessories.getText().toString(),
                OperatingSystem.getText().toString(), SpecialFeatures.getText().toString(), OtherInfo.getText().toString());

        //validate form
        boolean cancel = false;

        //array of Views to highlight any invalid input
        View[] focusViews = new View[3];
        for (int i = 0; i < focusViews.length; i++){
            focusViews[i] = null;
        }

        //check for name entry (required)
        if (TextUtils.isEmpty(newItem.getName())) {
            Name.setError(getString(R.string.error_field_required));
            focusViews[0] = Name;
            cancel = true;
        }

        // Check for serial entry (required)
        if (TextUtils.isEmpty(newItem.getSerial())) {
            Serial.setError(getString(R.string.error_field_required));
            focusViews[1] = Serial;
            cancel = true;
        }


        /*
        check format of pages entry -- must be number or "N/A"
        (note: N/A is filled in by default on empty
         */
        String pages = newItem.getPages();
        if (!(TextUtils.isEmpty(pages)) && (!(pages.equals("N/A")))){
            try{
                Integer.parseInt(pages);
            }
            catch (NumberFormatException e){
                cancel = true;
                Pages.setError(getString(R.string.number_format_improper));
                focusViews[2] = Pages;
            }
        }

        //activity for cancellation
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            // set focus to first field.  Others are clickable
            for (int i = 0; i < focusViews.length; i++){
                if (focusViews[i] != null){
                    focusViews[i].requestFocus();
                    break;
                }
            }
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform edit attempt.
            mEditDetailStatusMessageView.setText(R.string.ItemAddAttempt);
            showProgress(true);

            //pass new Item object to async task
            iEditItem = new ItemEditTask();
            iEditItem.execute(newItem);

        }
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mEditDetailStatusView.setVisibility(View.VISIBLE);
            mEditDetailStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mEditDetailStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mEditDetailView.setVisibility(View.VISIBLE);
            mEditDetailView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mEditDetailView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mEditDetailStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mEditDetailView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous task to edit item data
     * the user.
     */
    public class ItemEditTask extends AsyncTask<Item, Void, Boolean> {
        private String response = "";
        Item newItem;


        @Override
        protected Boolean doInBackground(Item... items) {
            //PHP address for editing
            String register = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/editItem";

            //get item object
            newItem = items[0];

            //get item object data
            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("id", newItem.getId()));
            parameters.add(new BasicNameValuePair("name", newItem.getName()));
            parameters.add(new BasicNameValuePair("serial", newItem.getSerial()));
            parameters.add(new BasicNameValuePair("accessories", newItem.getAccessories()));
            parameters.add(new BasicNameValuePair("specialFeatures", newItem.getSpecialFeatures()));
            parameters.add(new BasicNameValuePair("operatingSystem", newItem.getOperatingSystem()));
            parameters.add(new BasicNameValuePair("pages", newItem.getPages()));
            parameters.add(new BasicNameValuePair("otherInfo", newItem.getOtherInfo()));


            //post changes to database
            JSONObject json = jsonParser.makeHttpRequest(register, "POST", parameters);


            Boolean errors = true;
            try{
                response = json.getString("message");
                errors = json.getBoolean("error");
            }
            catch (JSONException e) {
                errors = true;
            }

            return errors;
        }

        @Override
        protected void onPostExecute(final Boolean errors) {
            iEditItem = null;
            showProgress(false);

            boolean success = !errors;  //no errors = success

            //if edit successful, inform user and return to detail view so user can confirm
            if (success) {
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, response, duration);
                toast.show();
                Intent i = new Intent(getApplicationContext(), ItemView.class);
                i.putExtra("id", newItem.getId());
                Utility.addToIntent(i, user, API);
                startActivity(i);
            //upon failure, alert user, and return to edit page
            } else {
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, response, duration);
                toast.show();
                //finish();
            }
        }
        //reset method for cancellation
        @Override
        protected void onCancelled() {
            iEditItem = null;
            showProgress(false);
        }
    }


}
